package pl.iachoo.ctl.tabory.dao.hibernate.services;

import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import pl.iachoo.ctl.tabory.dao.hibernate.interfaces.ICompositionService;
import pl.iachoo.ctl.tabory.dao.hibernate.vo.CompositionVO;
import pl.iachoo.ctl.tabory.dao.hibernate.vo.VagonVO;

public class CompositionServiceImpl extends BaseDaoService<CompositionVO>
		implements ICompositionService {

	private final static Logger log = Logger
			.getLogger(CompositionServiceImpl.class);

	private static CompositionServiceImpl instance;

	private CompositionServiceImpl() {

	}

	public static CompositionServiceImpl getInstance() {
		if (instance == null) {
			log.info("Creating new instance of service: CompositionServiceImpl");
			instance = new CompositionServiceImpl();
		}
		log.info("Retriving service: CompositionServiceImpl.");
		return instance;
	}

	@Override
	public List<CompositionVO> getAllCompositions() throws Exception {
		log.debug("Getting all compositions.");
		CompositionVO criterion = new CompositionVO();
		criterion.setDeleted(false);
		List<CompositionVO> loadList = loadList(CompositionVO.class, criterion);
		return loadList;
	}

	@Override
	public CompositionVO getComposition(int id) throws Exception {
		log.debug("Getting composition for id: " + id);
		CompositionVO composition = load(CompositionVO.class, id);
		return composition;
	}

	@Override
	public CompositionVO saveOrUpdateComposition(CompositionVO composition)
			throws Exception {
		log.debug("Saving/Updating composition: " + composition);
		Set<VagonVO> vagonVOs = composition.getVagonVOs();
		for (VagonVO vagonVO : vagonVOs) {
			vagonVO.setCompositionVO(composition);
		}
		composition.setVagonVOs(vagonVOs);
		saveOrUpdate(composition);
		return composition;
	}

}
